package eu.ec.ellipcis.integration.ws.client;

import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Validator;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.MessagingTemplate;
import org.springframework.integration.support.MessageBuilder;

import eu.ec.ellipcis.integration.ws.client.domain.AccountBalanceRequest;

public class AccountRequestClient {


    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("client.xml");

        MessageChannel channel = context.getBean("accountRequests", MessageChannel.class);
        MessagingTemplate messagingTemplate = new MessagingTemplate();
        AccountBalanceRequest request = new AccountBalanceRequest();
        request.setName("Fred Flinstone");
        request.setNumber("123456789");
        Message<String> soapMessage = MessageBuilder
                .withPayload(marshallToXml(request))
                .setCorrelationId(123456789)
                .build();
        Message<?> message = messagingTemplate.sendAndReceive(channel, soapMessage);
        //messagingTemplate.send(channel, soapMessage);
        System.err.println("Message Sent");
        System.out.println(message.getPayload());
    }

    public static String marshallToXml(AccountBalanceRequest request) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(AccountBalanceRequest.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(request, writer);
        return writer.toString();
    }

}
